package com.itcoon.cloud.framework.transform.assemble.handler.parameterized;

import com.itcoon.cloud.framework.transform.assemble.handler.AssembleHandlerComposite;
import com.itcoon.cloud.framework.transform.definition.InjectDefinition;
import com.itcoon.cloud.framework.utils.SpringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TargetMapHandlerTarget implements ParameterizedTargetTypeHandler {

    @Override
    public boolean support(ParameterizedType targetPropertyType, Object originGetterValue, List<InjectDefinition> injectInfos) {
        return Map.class.isAssignableFrom((Class<?>)targetPropertyType.getRawType());
    }

    @Override
    public Object handle(ParameterizedType targetPropertyType, Object originGetterValue, String[] ignoreProperties, List<InjectDefinition> injectInfos) {
        Type[] types = targetPropertyType.getActualTypeArguments();
        Map<?, ?> sourceMap = (Map<?, ?>) originGetterValue;
        AssembleHandlerComposite composite = SpringUtils.getBean(AssembleHandlerComposite.class);
        Map<Object, Object> targetMap = new HashMap<>();
        for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {
            Object key = composite.handle(types[0], entry.getKey(), ignoreProperties, new ArrayList<>());
            Object value = composite.handle(types[1], entry.getValue(), ignoreProperties, new ArrayList<>());
            targetMap.put(key, value);
        }
        return targetMap;
    }
}
